/*
 * @Author: your name
 * @Date: 2022-04-22 14:55:27
 * @LastEditTime: 2022-04-26 13:32:47
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \mallAdmin\src\app\main\used-store\used-marketing-manage\second-user-coupon\second-user-coupon.component.ts
 */
import { Component, OnInit } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd/message';
import { SecondCouponService } from '../services/second-coupon.service';
import { userCouponStatusArr } from '../used-marketing-manage.pipe';
import { PermissionService } from '../../../../service/permission.service';

@Component({
  selector: 'app-second-user-coupon',
  templateUrl: './second-user-coupon.component.html',
  styleUrls: ['./second-user-coupon.component.scss']
})
export class SecondUserCouponComponent implements OnInit {

  searchOptions = [
    { type: 1, labelText: '用户优惠券ID', valueKey: 'id', value: '' },
    { type: 1, labelText: '客户', valueKey: 'userInfo', value: '', placeholder: '请输入客户名称/昵称/ID' },
    { type: 1, labelText: '优惠券ID', valueKey: 'couponNo', value: '' },
    { type: 1, labelText: '关联单号', valueKey: 'orderNum', value: '' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'statusStr',
      value: [],
      multiple: true,
      notTostr: false,
      selectOptions: [...userCouponStatusArr],
    },
    { type: 3, labelText: '领取时间', valueKey: ['getBeginTime', 'getEndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '过期时间', valueKey: ['endBeginTime', 'endTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '使用时间', valueKey: ['useBeginTime', 'useEndTime'], value: [], isTimeSelect: true }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  }

  // 撤回用户用券 Modal
  isWithdrawVisible = false;
  withdrawLoading = false;
  withdrawType: number = 0;
  withdrawItem: any = {};
  withdrawParams: any = {
    remark: ''
  };

  // Tbale check
  checked = false;
  indeterminate = false;
  listOfCurrentPageData: readonly any[] = [];
  setOfCheckedId = new Set<number>();

  constructor(
    private message: NzMessageService,
    public permission: PermissionService,
    private services: SecondCouponService
  ) { }

  ngOnInit(): void {
    // this.loadTable();
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      type: 2,
      pageNum: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const res: any = await this.services.getUserCouponList(params);
    this.tableParams.loading = false;

    if (res.code === 0) {
      const { list, total } = res.data || {};
      this.tableParams.tableData = list || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData(params: any) {
    this.setOfCheckedId.clear();
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * 撤回用户券
   * ----------------------------------------------------------------
   */
  showWithdrawModal(type: number, item?: any) {
    if (type === 0 && !this.setOfCheckedId.size) {
      this.message.warning('请先勾选所需操作项');
      return
    }

    this.withdrawType = type;
    this.withdrawItem = item;
    this.withdrawParams.remark = '';
    this.isWithdrawVisible = true;
  }

  async subWithdraw() {
    if (this.withdrawParams.remark === '') {
      this.message.warning('请先输入撤回原因');
      return
    }
    let params: any = {
      remark: this.withdrawParams.remark,
      type: 2,
      ids: []
    }
    params.ids = this.withdrawType === 0 ? [...this.setOfCheckedId] : [this.withdrawItem.id];

    this.withdrawLoading = true;
    const res: any = await this.services.stopUserCoupon(params);
    this.withdrawLoading = false;

    if (res.code === 0) {
      this.message.success('操作成功');
      this.isWithdrawVisible = false;
      this.setOfCheckedId.clear();
      this.loadTable();
    } else {
      this.message.error(res.message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * Table 勾选
   * ----------------------------------------------------------------
   */
  updateCheckedSet(id: number, checked: boolean): void {
    if (checked) {
      this.setOfCheckedId.add(id);
    } else {
      this.setOfCheckedId.delete(id);
    }
  }

  onItemChecked(id: number, checked: boolean): void {
    this.updateCheckedSet(id, checked);
    this.refreshCheckedStatus();
  }

  onAllChecked(value: boolean): void {
    this.listOfCurrentPageData
      .filter(({ status }) => status === 1)
      .forEach(item => this.updateCheckedSet(item.id, value));
    this.refreshCheckedStatus();
  }

  onCurrentPageDataChange($event: readonly any[]): void {
    this.listOfCurrentPageData = $event;
    this.refreshCheckedStatus();
  }

  refreshCheckedStatus(): void {
    const listOfEnabledData = this.listOfCurrentPageData.filter(({ status }) => status === 1);
    this.checked = listOfEnabledData.every(item => this.setOfCheckedId.has(item.id)) && listOfEnabledData.length > 0;
    this.indeterminate = listOfEnabledData.some(item => this.setOfCheckedId.has(item.id)) && !this.checked;
  }
}
